const Router = require('koa-router');
const router = new Router();

router.get('/tree', async ctx => {
    const { getTree } = require('../models/quotationCategory');
    const res = await getTree(ctx.access_token)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    const { parseTree } = require('../libs/common')
    const treeData = parseTree(res.data.data)
    ctx.body = {
        code: 200,
        data: treeData,
        msg: 'ok'
    };
})
router.get('/all', async ctx => {
    const { getAll } = require('../models/quotationCategory');
    const res = await getAll(ctx.access_token)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: res.data.data.map(item => JSON.parse(item)),
        msg: 'ok'
    };
})
router.get('/', async ctx => {
    const { get } = require('../models/quotationCategory');
    const res = await get(ctx.access_token, ctx.query)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: {
            ...res.data,
            data: res.data.data.map(item => JSON.parse(item)),
        },
        msg: 'ok'
    };
})
router.get('/:id', async ctx => {
    const { getInfo } = require('../models/quotationCategory');
    const res = await getInfo(ctx.access_token, ctx.params.id)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: (res.data.data.map(item => JSON.parse(item)))[0],
        msg: 'ok'
    };
})
router.post('/', async ctx => {
    const { add } = require('../models/quotationCategory');
    const res = await add(ctx.access_token, ctx.request.body)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: res.data,
        msg: 'ok'
    };
})
router.delete('/', async ctx => {
    const { del } = require('../models/quotationCategory');
    const res = await del(ctx.access_token, ctx.query.id)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: res.data,
        msg: 'ok'
    };
})
router.put('/', async ctx => {
    const { update } = require('../models/quotationCategory');
    const res = await update(ctx.access_token, ctx.request.body)
    ctx.errcode(res.data.errcode, res.data.errmsg)
    ctx.body = {
        code: 200,
        data: res.data,
        msg: 'ok'
    };
})

module.exports = router.routes();